package com.data.permission.transf;

import com.data.permission.rule.DataRuleInfoComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @包名称 com.thrift.distributed.process
 * @类描述 <pre></pre>
 * @作者 zhangbo
 * @创建时间 2019/9/20
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           Lenovo        2019/9/20
 *     -----------------------------------------------------------
 * </pre>
 */
@Component
@Slf4j
@Order(value = 2)
public class ClientRun implements CommandLineRunner {

    @Autowired
    private ClientListener clientListener;

    @Autowired
    private DataRuleInfoComponent dataRuleInfoComponent;

    /*注册中心超时或重复检测休眠时间(服务列表丢失找回)*/
    @Value("${ZOOKEEPER.SERVICE.SLEEP.TIME:10000}")
    private int zookeeperServiceSleepTime;

    /*服务规则刷新延迟时间*/
    @Value("${RULE.REFRESH.TIME:30}")
    private long REFRESH_TIME;

    /*服务端地址检测延迟时间*/
    @Value("${REGIST.CHECK.TIME:30}")
    private long CHECK_TIME;

    public static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = new ScheduledThreadPoolExecutor(2);

    @Override
    public void run(String... strings) throws Exception {
        clientListener.init();
        COUNT_DOWN_LATCH.await();
        /*定时调度刷新服务地址*/
        SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(new RegistRunable(clientListener), CHECK_TIME, CHECK_TIME, TimeUnit.SECONDS);
        /*定时高度刷新规则*/
        SCHEDULED_EXECUTOR_SERVICE.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                log.info("开始刷新数据权限规则对象....");
                dataRuleInfoComponent.flushConditions();
                dataRuleInfoComponent.flushRules();
                log.info("数据权限规则对象刷新完成");
            }
        }, 0, REFRESH_TIME, TimeUnit.SECONDS);


    }
}
